package com.xyh.eduservice.controller;


import com.xyh.commonutils.R;
import com.xyh.eduservice.client.VodClient;
import com.xyh.eduservice.entity.EduVideo;
import com.xyh.eduservice.service.EduVideoService;
import com.xyh.servicebase.exceptionHandler.GuliException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-08-08
 */
@RestController
@RequestMapping("/eduservice/video")
//@CrossOrigin
public class EduVideoController {

    @Resource
    private VodClient vodClient;

    @Resource
    private EduVideoService videoService;
    //添加小节
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        videoService.save(eduVideo);
        return R.ok();
    }
    //删除小节
    // TODO 后面这个方法需要完善：删除小节的时候，同时把里面的视频删除(已完善)
    @DeleteMapping("/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = videoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();

        //判断小姐里面是否有视频id
        if (!StringUtils.isEmpty(videoSourceId)){
            //根据视频id，远程调用实现视频删除
            R result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode() == 20001){
                throw new GuliException(20001,"删除视频失败~~,熔断器执行");
            }
        }

        boolean b = videoService.removeById(videoId);
        return b ? R.ok():R.error();
    }
    //修改小节
    @PostMapping("/updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        videoService.updateById(eduVideo);
        return R.ok();
    }

    //根据 id 查询小节基本信息
    @GetMapping("/getVideoInfo/{videoId}")
    public R getVideo(@PathVariable String videoId){
        EduVideo video = videoService.getById(videoId);
        return R.ok().data("videoInfo",video);
    }


}

